import { login, getUserInfo } from '@/api/login';
import { setToken, getToken, removeToken } from '@/utils/cookie';
import permission from './permission';

const user = {
  state: {
    token: getToken(),
    roles: [],
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_USER: (state, user) => {
      localStorage.setItem('user', user);
    }
  },
  actions: {
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((res) => {
            console.log(res)
            if (res.data.success) {
              setToken(res.data.token);
              commit('SET_TOKEN', res.data.token);
              commit('SET_USER', userInfo.username);
              resolve();
            } else {
              reject(res.data);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    LogOut({ commit }) {
      removeToken();
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      commit('SET_USER', '');
    },
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            commit('SET_ROLES', res.data[0].role);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};

export default user;
